import { get, post, put, del, required, controller } from '../decorator/route'
import mongoose from 'mongoose'
const User = mongoose.model('User')
@controller('/admin')
export class AdminController {
  @post('/loging')
  @required({body: ['email', 'password']})
  async adminLogin(ctx, next) {
    let { email, password } = ctx.request.body
    let data = await User.findOne({
      email
    }).exec()

    if (!data) return (ctx.body ={ success: false, error: '该用户不存在' })

    let match = await data.comparePassword(password, data.password)
    if (!match) return (ctx.body ={ success: false, error: '密码错误' })
    if (data.role != 'admin') return (ctx.body ={ success: false, error: '不是管理员' })
    
    ctx.session.user = {
      _id: data._id,
      nickname: data.nickname,
      email: data.email,
      avatarUrl: data.avatarUrl
    }

    console.log(ctx.session.user)

    ctx.body = {
      success: true,
      data: {
        nickname: data.nickname,
        role: data.role,
        email: data.email,
        avatarUrl: data.avatarUrl
      }
    }
    
  }

  @post('/logout')
  async logout(ctx, next) {
    ctx.session.user = null
    ctx.body = {
      success: true
    }
  }
}